// payment
// var app;
// var common = require("../../../usl/token.js");
// var gains;
// var gain = require("../../../usl/tokenGain.js");
// // var conversation = require('../../../usl/conversation.js')  optionsId
// var baseUrl = 'https://minitest.17jxyx.com/api/v1/';
const app = getApp()
const connector = require('../../../../utils/connector.js')
const myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(19[0-9]{1})|(17[0-9]{1}))+\d{8})$/;

Page({

  /**
   * 页面的初始数据s
   */
  data: {
    user:{},
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    authorizationGets: "false",
    judge: "0",
    // viewType:"1",
    // judgeImg: "http://192.168.10.211:5113/Static/Images/Default/201911/7d90b0239884445abd544723ca196c17.gif",

  },
  userName(e) {
    this.setData({
      userName: e.detail.value
    })
    console.log(e.detail.value)

  },
  userPhone(e) {
    this.setData({
      userPhone: e.detail.value
    })
    console.log(e.detail.value)
  },

/**去选择地址 */
  accountsTopR(e){
    var that = this
    // var token = wx.getStorageSync('token');
    /**获取微信地址 */
    wx.chooseAddress({
      success: function (res) {
        let str = JSON.stringify(res)
        // wx.setStorageSync("user", res)
        let obj = {
          userName: res.userName,
          telNumber: res.telNumber,
          address: res.provinceName + res.cityName + res.countyName + res.detailInfo
        }
        that.setData({
          user: obj
        })
      },
      fail: function (err) {
        // console.log(err)
      }
    })
    wx.getSetting({
      success: res => {
        // console.log(res.authSetting['scope.address'])
        if (res.authSetting['scope.address'] == false) {
          that.setData({
            authorizationGets: "true",
          })
        }

      }
    })

   
  },
  /**增加 */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.accounts;
    let num = carts[index].num;
    num = num + 1;
    carts[index].num = num;
    let nums = 0;
    for (var i = 0; i < carts.length; i++) {
      nums = nums + carts[i].num * carts[i].price;
    }
    this.setData({
      accounts: carts,
      nums: nums.toFixed(2)
    });
    // wx.setStorage({
    //   key: "addCarts",
    //   data: carts
    // })
    // this.getTotalPrice();
  },
  /**减少 */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.accounts;
    let num = carts[index].num;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    
    let nums = 0;
    for (var i = 0; i < carts.length;i++){
      nums = nums + carts[i].num * carts[i].price;
    }
    this.setData({
      accounts: carts,
      nums: nums.toFixed(2)
    });
    // wx.setStorage({
    //   key: "addCarts",
    //   data: carts
    // })
    // this.getTotalPrice();
  },
// /**付款 */payment
  payment(e){
    var that = this;
    var cartNew = [];
    // var accounts = wx.getStorageSync('accountsCart');
    var accounts = that.data.accounts;
      let userAddre = that.data.user
      let userAddreObj = {
        name: userAddre.userName,
        phone: userAddre.telNumber,
        detail: userAddre.address
      }
      userAddress(that, userAddreObj)
    // let userAddreObj={}
    // if (accounts.length == 1 && accounts[0].send_type == 2){
    //   console.log("1111111111111111111111111111")
    //   let str = that.data.userName
    //   let numPhone = that.data.userPhone
    //   if (!str || str.replace(/\s*/g, '').length < 1){
    //     wx.showToast({
    //       title: "请输入取货人姓名",
    //       icon: 'none',
    //       duration: 1000
    //     })
    //     return false;
    //   }
    //   if (!numPhone || numPhone.replace(/\s*/g, '').length < 1) {
    //     wx.showToast({
    //       title: "请输入取货人手机号",
    //       icon: 'none',
    //       duration: 1000
    //     })
    //     return false;
    //   }
    //   if (numPhone.length < 11 || !myreg.test(numPhone)) {
    //     wx.showToast({
    //       title: "取货人手机号输入有误",
    //       icon: 'none',
    //       duration: 1000
    //     })
    //     return false
    //   }
    //   let userAddre = that.data.user
    //       userAddreObj = {
    //         name: that.data.userName,
    //         phone: that.data.userPhone,
    //         detail: ''
    //       }
          
    // }else{
    //   userAddreObj = {
    //     name: userAddre.userName,
    //     phone: userAddre.telNumber,
    //     detail: userAddre.address
    //   }
    // }
    // console.log(userAddreObj)
    // userAddress(that, userAddreObj)
    
    var buy_num = that.data.buy_num;
    // console.log(buy_num)
    // console.log(accounts)
    if (that.data.user.userName && that.data.user.userName != ''){
      for (var j = 0; j < accounts.length; j++) {
        if (!accounts[j].selected) {
          cartNew.push(accounts[j])
        }
      }
      var cartNewNum = 0;
      if (cartNew.length > 0) {
        for (var k = 0; k < cartNew.length; k++) {
          cartNewNum = cartNewNum + cartNew[k].num
        }
      }
      let accountsCart1;


      let arr = that.data.accounts;
      // console.log(arr)

      let arrs = [];
      for (var j = 0; j < arr.length; j++) {
        let obj = {}
        obj.product_id = arr[j].id;
        obj.count = arr[j].num;
        obj.type = 3;
        arrs.push(obj)
      }
      // console.log(arrs)

    
      console.log(arrs)
      //下单
      wx.request({
        url: app.conUser + '/order/place',
        data: {
          order_type:3,
          products: arrs,
        },
        header: {
          token: app.tokens
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        success: function (res) {
          console.log(res)
          if(res.data.order_id > 0){
            wx.setStorageSync('order_id', res.data.order_id);
            console.log(res.data.order_id)
            console.log(res.data)
            if (app.tokens) {
              //拉取微信支付
              wx.request({
                url: app.conUser + '/pay/pre_order',
                method: 'POST',
                header: {
                  token: app.tokens
                },
                data: {
                  id: res.data.order_id
                },
                success: function (ser) {
                  console.log(ser)
                  var preData = ser.data;
                  console.log(preData)
                  headlineBuyDelete()
                  //拉取微信支付
                  wx.requestPayment({
                    timeStamp: preData.timeStamp.toString(),
                    nonceStr: preData.nonceStr,
                    package: preData.package,
                    signType: preData.signType,
                    paySign: preData.paySign,
                    success: function (sss) {
                      console.log(sss)
                      // wx.navigateTo({
                      //   url: '/pages/oneself/order/order',
                      // })
                      wx.navigateBack({
                        delta: 1,
                      })
                    },
                    fail: function (error) {
                      console.log(error)
                      // wx.navigateTo({
                      //   url: '/pages/oneself/order/order',
                      // })
                      console.log(res.data.order_no)
                      wx.redirectTo({
                        url: '/pages/oneself/order/details/details?queryBean=' + JSON.stringify(res.data.order_no),
                      })
                    }
  
                  })
  
                }
              })
            }
          }else{
            wx.showToast({
              title: "下单失败,请联系客服",
              icon: 'none',
              duration: 1000
            })
          }
          
        },
        fail: function (res) {
        }
      });
    } else {
      wx.showModal({
        title: "错误",
        content: "请填写完整收货人信息",
        showCancel: false,
        success: function () {

        }
      })
    }
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // headlineBuy
    // var buy_num = wx.getStorageSync('buy_num')
    
    // if (buy_num == 1){
    //   let nums = 0;
    //   let accounts = wx.getStorageSync('accountsCart')
    //   let arr = []
    //   for (var i = 0; i < accounts.length; i++) {
    //     if (accounts[i].selected) {
    //       arr.push(accounts[i])
    //     }
    //   }
    //   for (var i = 0; i < arr.length; i++) {
    //     nums = nums + arr[i].num * arr[i].price
    //   }
    //   that.setData({
    //     accounts: arr,
    //     nums: nums.toFixed(2)
    //   })
    // }
    // if (buy_num == 2){
    //   let headlineBuy = wx.getStorageSync('headlineBuy')
    //   that.setData({
    //     accounts: headlineBuy,
    //     nums: headlineBuy[0].price
    //   })
    // }
    // that.setData({
    //   buy_num: buy_num
    // })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const that = this
    userAddr(that)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
    var that = this

    wx.getSetting({
      success: res => {
        // console.log(res.authSetting['scope.address'])
        if (res.authSetting['scope.address']){
          that.setData({
            authorizationGets: "false",
          })
        }
       
      }
    })
   
    var buy_num = wx.getStorageSync('buy_num')
    // conversation.conversation(that)
    if (buy_num == 1) {
      let nums = 0;
      let accounts = wx.getStorageSync('accountsCart')
      if (accounts.length<1){
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
      let arr = []
      for (var i = 0; i < accounts.length; i++) {
        if (accounts[i].selected) {
          arr.push(accounts[i])
        }
      }
      for (var i = 0; i < arr.length; i++) {
        nums = nums + arr[i].num * arr[i].price
      }
      that.setData({
        accounts: arr,
        nums: nums.toFixed(2)
      })
    }

    if (buy_num == 2) {
      let headlineBuy = wx.getStorageSync('headlineBuy')
      if (headlineBuy.length<1){
        wx.switchTab({
          url: '/pages/index/index',
        })
      }else{
        for (var p = 0; p < headlineBuy.length;p++){
          headlineBuy[p].num = 1
        }
        that.setData({
          accounts: headlineBuy,
          nums: headlineBuy[0].price
        })
      }
    }
    that.setData({
      buy_num: buy_num
    })
    // common.myfunc(that);  //最后我们需要执行才能生效！
    var user;
    // wx.request({
    //   url: 'https://minitest.17jxyx.com/api/v1/address/user',//这个地址好像只能https的
    //   method: "POST",
    //   header: {
    //     token: wx.getStorageSync('token')
    //   },
    //   success: function (res) {
    //     user = res.data
    //     that.setData({
    //       user: user
    //     })
    //   },
    //   fail: function () {
    //   }
    // })

    if(user){
      this.setData({
        user:user
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {
    var that = this
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
//获取用户地址
function userAddr(that) {
  connector.getFunc(connector.connector().userAddr, '', "get", app.tokens, function (res) {
    if (res.statusCode == 200) {
      // console.log(res.data.address)
      console.log(res)
      if(res.data.address){
        let obj = {
          userName: res.data.address.full_name,
          telNumber: res.data.address.phone,
          address: res.data.address.address
        }
        that.setData({
          user: obj
        })
      }
      
      // if (res.data.length > 0){
      //   console.log("获取成功")
      // }

    }
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}

//上传地址
function userAddress(that, address) {
  // const shoppingIds = {
  //   product_id: shoppingId
  // }
  // console.log(address)
  connector.getFunc(connector.connector().userAddress, address, "post", app.tokens, function (res) {
    if (res.statusCode == 200) {
      // console.log(res.data)
      // console.log(res)

    }
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}
//清空
function headlineBuyDelete(){
  wx.setStorageSync('headlineBuy',[])
}